package net.peihuan.controller;

import net.peihuan.entity.Article;
import net.peihuan.entity.ArticleTag;
import net.peihuan.service.ArticleService;
import net.peihuan.service.ArticleTagService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleTagService articleTagService;


    /**
     * 查询某个文章
     * @param request
     * @return
     */
    @RequestMapping("/selectArticle")
    @ResponseBody
    public Article selectArticle(HttpServletRequest request){
        String id=request.getParameter("id");
        if(id==null||id.equals(""))
            return null;
        int id_int=Integer.parseInt(id);
        return articleService.findById(id_int);
    }

    @RequestMapping("/addOrUpdateArticle")
    @ResponseBody
    public String addOrUpdateArticle(HttpServletRequest request){

        String id=request.getParameter("id");
        String title=request.getParameter("title");
        String content=request.getParameter("content");
        String category=request.getParameter("category");
        String tags=request.getParameter("tags");
        String recommend=request.getParameter("reommend");

        String[] tag=tags.split(",");

        int categoryid=0;
        int weight=0;
        int[] tagids=new int[tag.length];
        try {
            categoryid=Integer.valueOf(category);
            for(int i=0;i<tag.length;i++){
                tagids[i]=Integer.valueOf(tag[i]);
            }
            weight=Integer.valueOf(recommend);
        }catch (Exception ignored){

        }

        //设置文章
        Article article=new Article();
        article.setCategoryid(categoryid);
        article.setContent(content);
        article.setTitle(title);
        article.setWeight(weight);

        if(!"".equals(id)){
            //如果id不为空，那么应该为更新
            article.setArticleid(Integer.parseInt(id));
            return updateArticle(article,tagids);
        }else{
            //新添文章
            article.setArticleid((int)System.currentTimeMillis());  //以时间作为主键
            return addArticle(article,tagids);
        }


    }

    //新添文章
    private String addArticle(Article article,int[] tagids){
        int count=0;
        if(articleService.save(article)==1){
            //插入文章-标签关系
            for(int tagid:tagids){
                ArticleTag articletag=new ArticleTag();
                articletag.setArticleid(article.getArticleid());
                articletag.setTagid(tagid);
                if(articleTagService.save(articletag)==1)
                    count++;
            }
            if (count!=tagids.length){
                return "有"+String.valueOf(tagids.length-count)+"个新标签未成功添加";
            }else{
                return "success";
            }
        }else{
            return "新建文章失败";
        }
    }
    //更新文章
    private String updateArticle(Article article,int[] tagids){
        int articleid=article.getArticleid();
        if(!articleService.update(article))
            return "文章更新失败";
        //更新文章-标签关系表
        int count=0;
        if(articleTagService.deleteByArticleId(articleid)>0){
            //原来的标签删除成功
            for(int tagid:tagids){
                ArticleTag articletag=new ArticleTag();
                articletag.setArticleid(articleid);
                articletag.setTagid(tagid);
                if(articleTagService.save(articletag)==1)
                    count++;
            }
            if (count!=tagids.length){
                return "有"+String.valueOf(tagids.length-count)+"个新标签未成功添加";
            }else{
                return "success";
            }
        }else{
            return "原本标签删除失败";
        }
    }

    /**
     * 查询所有文章
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectAllArticles")
    @ResponseBody
    public Map<String,Object> SelectAllArticles(HttpServletRequest request){
        //总文章数
        Integer count=articleService.countArticles();
        //一页显示的文章数
        Integer perPage=10;
        //当前页数
        Integer page;
        String p = request.getParameter("topage");
        String per=request.getParameter("perpage");
        try {
            page=Integer.valueOf(p);
            perPage=Integer.parseInt(per);
        }catch (Exception e){
            page=1;
        }
        //总页数
        Integer totalPages=count%perPage==0?count/perPage:count/perPage+1;
        //本叶起始序号
        Integer beginIndex=(page-1)*perPage;




        Map<String,Object> map = new HashMap<String,Object>();

        List<Article> result=articleService.findAllWithDetails(beginIndex,perPage);

        map.put( "totalPages",totalPages);
        map.put( "page", page);
        map.put( "articles",result);

        return  map;
    }

    //归档
    @RequestMapping("/selectArchive")
    @ResponseBody
    public List<Article> selectArchive(){
        return articleService.findAllBaseResultMap();
    }

    //查询文章总数
    @RequestMapping("/count")
    @ResponseBody
    public int count(){
        return  articleService.countArticles();
    }

    //查询某篇文章的附近两篇文章
    @RequestMapping("/selectNearbyArticles")
    @ResponseBody
    public List<Article> selectNearbyArticles(HttpServletRequest request){
        String time=request.getParameter("time");
        List<Article> articles=articleService.findNearby(time);
        return articles;
    }

    /**
     * 删除一个文章
     * @param request
     * @return 1 删除成功   0 失败
     */
    @RequestMapping(value = "/delectArticle")
    @ResponseBody
    public int deletctArticle(HttpServletRequest request) {

        if (!request.getParameter("id").equals("undefined")) {
            int id = Integer.valueOf((String) request.getParameter("id"));
            if (articleService.delete(id)) {
                return 1;
            } else {
                return 0;
            }
        }else{
            return 0;
        }
    }

    @RequestMapping("/selectByCategoryalias")
    @ResponseBody
    public List<Article> selectByCategoryalias(HttpServletRequest request){
        if(request.getParameter("alias")!=null)
            return  articleService.findByCategoryAlias(request.getParameter("alias"));
        else
            return null;
    }
    @RequestMapping("/selectByTagalias")
    @ResponseBody
    public List<Article> selectByTagalias(HttpServletRequest request){
        if(request.getParameter("alias")!=null)
            return  articleService.findByTagAlias(request.getParameter("alias"));
        else
            return null;
    }

    private Logger logger = Logger.getLogger(this.getClass());

    @RequestMapping(value = "/uploadImgg")
    @ResponseBody
    public Map<String,Object> upLoad(HttpServletRequest request) {
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        Map<String,Object> map = new HashMap<String,Object>();
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            List<String> data = new ArrayList<String>();
            while(iter.hasNext()){
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名 ,加“upload/”为了上传到upload文件夹下
                        /*String fileName = "upload/" + file.getOriginalFilename(); */

                        long time=System.currentTimeMillis();
                        //相对路径
                        String fileName = "upload/" + time + myFileName.substring(myFileName.lastIndexOf("."), myFileName.length());
                        logger.info("上传文件：相对路径："+ fileName);
                        //绝对路径用于前端显示
                        String fontFileName = request.getScheme() + "://" + request.getServerName()
                                + request.getContextPath() + "/upload/" + time + myFileName.substring(myFileName.lastIndexOf("."), myFileName.length());
                        logger.info("上传文件：绝对路径："+ fileName);
                        //定义上传路径
                        String appRoot = request.getSession().getServletContext().getRealPath("") + File.separator;
                       // System.out.println("appRoot:" + appRoot);
                        /*String appRoot = "E:/workspace/Travel/src/main/webapp/";*/
                        String path = appRoot + fileName;
                       // System.out.println("fileName:" + fileName);
                        logger.info("上传文件:上传路径："+path);
                        File localFile = new File(path);
                        if(!localFile.exists()) {
                            localFile.mkdirs();
                        } try {
                            file.transferTo(localFile);
                            data.add(fontFileName);
                        } catch (Exception e) {
                            logger.error(e);
                            e.printStackTrace();
                            map.put("errno", 1);
                            map.put("data", data);

                            return map;
                        }
                    }
                }
            }
            map.put("errno", 0);
            map.put("data", data);
        }
        return map;
    }

    private static Map<Integer,Map> map =new HashMap<Integer,Map>();
    @RequestMapping("/pvCount")
    public void pvCount(){
        //  map< 文章id , map<ip , 次数> >
    }

}